using System;
using System.Threading.Tasks;
using ERP.ProductionManage;
using ERP.ProductionManage.Dtos;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Volo.Abp.AspNetCore.Mvc;

namespace ERP.Web.Controllers
{
    /// <summary>
    /// 生产退料控制器
    /// </summary>
    public class ProductionReturnController : AbpController
    {
        private readonly IProductionReturnService _productionReturnService;
        private readonly ILogger<ProductionReturnController> _logger;

        public ProductionReturnController(
            IProductionReturnService productionReturnService,
            ILogger<ProductionReturnController> logger)
        {
            _productionReturnService = productionReturnService;
            _logger = logger;
        }

        /// <summary>
        /// 生产退料管理页面
        /// </summary>
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 生产退料表单页面
        /// </summary>
        public IActionResult Form()
        {
            return View();
        }

        /// <summary>
        /// 获取生产退料分页列表
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> GetList(GetProductionReturnInputDto input)
        {
            try
            {
                var result = await _productionReturnService.GetListAsync(input);
                return Json(new
                {
                    code = 0,
                    msg = "",
                    count = result.TotalCount,
                    data = result.Items
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取生产退料列表失败");
                return Json(new { code = 1, msg = ex.Message });
            }
        }

        /// <summary>
        /// 获取生产退料详情
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetProductionReturn(int id)
        {
            try
            {
                var result = await _productionReturnService.GetAsync(id);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取生产退料详情失败，ID: {Id}", id);
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 创建生产退料
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> CreateProductionReturn(CreateProductionReturnDto input)
        {
            try
            {
                var result = await _productionReturnService.CreateAsync(input);
                _logger.LogInformation("创建生产退料成功，ID: {Id}", result.Id);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建生产退料失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 更新生产退料
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> UpdateProductionReturn(int id, UpdateProductionReturnDto input)
        {
            try
            {
                var result = await _productionReturnService.UpdateAsync(id, input);
                _logger.LogInformation("更新生产退料成功，ID: {Id}", id);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新生产退料失败，ID: {Id}", id);
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 删除生产退料
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> DeleteProductionReturn(int id)
        {
            try
            {
                await _productionReturnService.DeleteAsync(id);
                _logger.LogInformation("删除生产退料成功，ID: {Id}", id);
                return Json(new { success = true });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除生产退料失败，ID: {Id}", id);
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 生成退料单编号
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GenerateReturnCode()
        {
            try
            {
                var code = await _productionReturnService.GenerateReturnCodeAsync();
                return Json(new { success = true, data = code });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成退料单编号失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 获取退料明细列表
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> GetReturnDetails(int returnId)
        {
            try
            {
                var result = await _productionReturnService.GetReturnDetailsAsync(returnId);
                return Json(new
                {
                    code = 0,
                    msg = "",
                    count = result.Count,
                    data = result
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取退料明细列表失败，退料ID: {ReturnId}", returnId);
                return Json(new { code = 1, msg = ex.Message });
            }
        }

        /// <summary>
        /// 添加退料明细
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> CreateReturnDetail(CreateProductionReturnDetailDto input)
        {
            try
            {
                var result = await _productionReturnService.CreateReturnDetailAsync(input);
                _logger.LogInformation("添加退料明细成功，ID: {Id}", result.Id);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加退料明细失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 删除退料明细
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> DeleteReturnDetail(int detailId)
        {
            try
            {
                await _productionReturnService.DeleteReturnDetailAsync(detailId);
                _logger.LogInformation("删除退料明细成功，ID: {Id}", detailId);
                return Json(new { success = true });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除退料明细失败，ID: {Id}", detailId);
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 执行退料操作
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> ExecuteReturn(int returnId)
        {
            try
            {
                await _productionReturnService.ExecuteReturnAsync(returnId);
                _logger.LogInformation("执行退料操作成功，退料ID: {ReturnId}", returnId);
                return Json(new { success = true, message = "退料操作执行成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "执行退料操作失败，退料ID: {ReturnId}", returnId);
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 获取仓库选择列表
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetWarehousesForSelect()
        {
            try
            {
                var result = await _productionReturnService.GetWarehousesForSelectAsync();
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取仓库选择列表失败");
                return Json(new { success = false, message = ex.Message });
            }
        }



        /// <summary>
        /// 获取物料选择列表（用于退料明细）
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetMaterialsForReturn([FromQuery] GetProductSelectInputDto input)
        {
            try
            {
                var result = await _productionReturnService.GetMaterialsForReturnAsync(input);
                return Json(new { 
                    code = 0, 
                    msg = "获取成功", 
                    count = result.TotalCount,
                    data = result.Items 
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取物料选择列表失败");
                return Json(new { code = 1, msg = "获取失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 获取生产工单选择列表
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetWorkOrdersForSelect([FromQuery] GetWorkOrderSelectInputDto input)
        {
            try
            {
                var result = await _productionReturnService.GetWorkOrdersForSelectAsync(input);
                return Json(new { 
                    code = 0, 
                    msg = "获取成功", 
                    count = result.TotalCount,
                    data = result.Items 
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取生产工单选择列表失败");
                return Json(new { code = 1, msg = "获取失败：" + ex.Message });
            }
        }
    }
} 